import type { SysMenu } from "@/views/domain/admin/api/sysMenu";
import { getSessionMenu } from "@/views/domain/session/api/session";

export const getAsyncRoutes = async (): Promise<any[]> => {
  const { code, data } = await getSessionMenu();
  if (code !== 0) {
    return [];
  }

  return data.list.map(item => sysMenuToRoute(item));
};

const sysMenuToRoute = (item: SysMenu, showParent = false): any => {
  return {
    icon: item.icon,
    title: item.title,
    path: item.routePath,
    name: item.routeName,
    component: getComponent(item.component),
    hidden: item.isHide < 0,
    redirect: item.redirect,
    meta: {
      icon: item.icon,
      title: item.title,
      rank: item.order,
      showParent: showParent
    },
    children: item.children?.map(child => sysMenuToRoute(child, true))
  };
};

export const getComponent = (component?: string) => {
  if (!component || component === "") {
    return "/error/404";
  } else if (component.toLowerCase() === "layout") {
    return component;
  } else if (component.startsWith("/") || component.startsWith("./")) {
    return component;
  }
  return "/src/views/" + component + ".vue";
};
